/************************************************************************************/
/*  Program name CAPPOIMP_ORG_STRUCT_ELEMENT.sql                                */
/*  Creater:  CHAN BILLY KA KEUNG (PCCW - UniHub)                                   */
/*************   History   *************************                                */
/* 24 MAY 2006				       First created                                    */
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;
ALTER TRIGGER HR_PA_MAINTAIN_ORG_HIST_BRI DISABLE;
ALTER TRIGGER HR_PA_MAINTN_ORGHIER_HIST_BRI DISABLE;
ALTER TRIGGER PA_MAINTAIN_ORG_HIST_BRD DISABLE;
ALTER TRIGGER PER_ORG_STRUCTURE_ELEMENTS_OVN DISABLE;
ALTER TRIGGER PER_ORG_STRUCTURE_ELEMENTS_WHO DISABLE;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPPOIMP_ORG_STRUCT_ELEMENT';

	lv_Scc_Count	NUMBER	:=	0;
	lv_Err_Count	NUMBER	:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	lv_seq_id		NUMBER;
	
	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_PO_ORG_STRUCT_ELEMENT
	FOR UPDATE;
		
	
BEGIN
	FOR C1 IN Cur_F LOOP
		BEGIN
			
			SELECT PER_ORG_STRUCTURE_ELEMENTS_S.NEXTVAL
			INTO lv_seq_id
			FROM DUAL;
			
			UPDATE CRST_PO_ORG_STRUCT_ELEMENT
			SET ORG_STRUCTURE_ELEMENT_ID_N = lv_seq_id
			WHERE ORG_STRUCTURE_ELEMENT_ID = C1.ORG_STRUCTURE_ELEMENT_ID;
						
			INSERT INTO PER_ORG_STRUCTURE_ELEMENTS
			VALUES
			(
			lv_seq_id,
			CAPBRIMP_MAPPING.GetBGMapping(C1.BUSINESS_GROUP_ID),
			C1.ORGANIZATION_ID_PARENT,
			CAPPOIMP_MAPPING.GetOrgStructureVersionMapping(C1.ORG_STRUCTURE_VERSION_ID),
			CAPBRIMP_MAPPING.GetOrgMapping(C1.ORGANIZATION_ID_CHILD),
			C1.REQUEST_ID                    ,
			C1.PROGRAM_APPLICATION_ID        ,
			C1.PROGRAM_ID                    ,
			C1.PROGRAM_UPDATE_DATE           ,
			C1.LAST_UPDATE_DATE              ,
			C1.LAST_UPDATED_BY               ,
			C1.LAST_UPDATE_LOGIN             ,
			C1.CREATED_BY                    ,
			C1.CREATION_DATE                 ,
			C1.OBJECT_VERSION_NUMBER         ,
			C1.POSITION_CONTROL_ENABLED_FLAG , 
			C1.PARTY_ID   					     
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;

	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;
	
	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);
	
	COMMIT;
END;
/

ALTER TRIGGER HR_PA_MAINTAIN_ORG_HIST_BRI ENABLE;
ALTER TRIGGER HR_PA_MAINTN_ORGHIER_HIST_BRI ENABLE;
ALTER TRIGGER PA_MAINTAIN_ORG_HIST_BRD ENABLE;
ALTER TRIGGER PER_ORG_STRUCTURE_ELEMENTS_OVN ENABLE;
ALTER TRIGGER PER_ORG_STRUCTURE_ELEMENTS_WHO ENABLE;